package ass.web;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ass.beans.UserBean;
import ass.dao.support.UserDAOImpl;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String username = (String) request.getParameter("username");
		String password = (String) request.getParameter("password");

		UserDAOImpl userDAOImpl = new UserDAOImpl();
		UserBean userBean = userDAOImpl.getUser(username);

//		response.setContentType("text/html");// from response, set content type
//		PrintWriter out = response.getWriter();// from response, get output
//												// writer
//		out.write(userBean.getPassword() +"=" + password);
//
//		out.close();
//		&& (userBean.getActive().equals ("") || userBean.getActive()==null)
		if (userBean.getPassword().equals(password) &&  userBean.getActive().equals ("Y")) {
			String nextJSP = "";
			HttpSession session = request.getSession(true);
			session.setMaxInactiveInterval(-1);
			session.setAttribute("username", username);
			if (userBean.getIs_owner()== "") {
				nextJSP = "/userPanel.jsp";
			}else {
				nextJSP = "/ownerPanel.jsp";
			}
			
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
			dispatcher.forward(request, response);
		}else {
			String nextJSP = "";
			nextJSP = "/index.jsp";
			if (userBean.getActive() != "N") { 
				request.setAttribute("invalid_password",  "<font color='red'>username or password invalid </font>");
			}else {
				request.setAttribute("invalid_password",  "<font color='red'>please confirm your email</font>");
			}
			RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
			dispatcher.forward(request, response);
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		doGet(request,response);
	}

}
